import numpy as np
import pandas as pd
import random
from odps import ODPS
import time
from hyperopt import fmin, tpe, hp, STATUS_OK, Trials
import pandas as pd



def get_odps_data(table_name=None, is_sample=False, sample_size=1000, columns=None, sample_quantile=1):
    # if table_name is None or table_name == '':
    #     table_name = 'cnalgo_adx_dynamic_bid_public_dataset_ipinyou_imp_20130607_testing_set'
    t1 = time.time()
    print("[{}] start reading data...".format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
    print("table_name: ", table_name)
    df = odps_reader(table_name)
    print("[{}] data loaded, time elapsed: {:.2f} s.".format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), time.time() - t1))
    if is_sample:
        df = df.sample(n=sample_size)
    if columns is not None and len(columns) > 0:
        df = df[columns]
    return df
 
def OneShot(current_reserve, bid_price, p1, p2, p3, p4):
    if current_reserve > bid_price:
        next_reserve = current_reserve * (1 - p1)
    elif current_reserve > bid_price - p4:
        next_reserve = current_reserve * (1 + p2)
    else:
        next_reserve = current_reserve * (1 + p3)
    return next_reserve

def objective(params):
    p1 = params['p1']
    p2 = params['p2']
    p3 = params['p3']
    p4 = params['p4']
    p5 = params['p5']
    settle = 2
    reserve_price21 = p5
    income = 0

    global bidprice_21_list
    for i in range(len(bidprice_21_list)):
        if bidprice_21_list[i] >= reserve_price21:
            if settle == 1:
                income += bidprice_21_list[i]
            if settle == 2:
                income += reserve_price21
        reserve_price21 = OneShot(reserve_price21, bidprice_21_list[i], p1, p2, p3, p4)

    avg_income = income/len(bidprice_21_list) * (-1)

    return {'loss': avg_income, 'status': STATUS_OK}


if __name__ == '__main__':

    df = get_odps_data(table_name="iPinyou_train")
    df['bidding_price'] = df['bidding_price'].astype(int)
    global bidprice_21_list
    bidprice_21_list = df['bidding_price'].values.tolist()

    space = {
        'p1': hp.uniform('p1', 0, 1),
        'p2': hp.uniform('p2', 0, 1),
        'p3': hp.uniform('p3', 0, 1),
        'p4': hp.uniform('p4', 0, 100),
        'p5': hp.uniform('p5', 200, 400)
    }

    trials = Trials()
    best = fmin(objective, space, algo=tpe.suggest, max_evals=500, trials=trials)
    print(best)


